<?php

namespace common\logics\order\handle;

use Yii;
use common\logics\order\OrderLogic;
use common\logics\order\OrderUnifiedLogic;

/**
 * 订单操作基础模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderBaseHandle extends \common\base\Model {

    use \common\traits\Constants;

    /**
     * @var const 订单操作类型
     */
    const HANDLE_CANCEL = 'cancel';
    const HANDLE_REFUND = 'refund';
    const HANDLE_RECEIVE = 'receive';
    const HANDLE_DELETE = 'delete';

    /**
     * @var integer 操作管理员ID
     */
    public $operator;

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var integer 订单ID
     */
    public $order_id;

    /**
     * @var string 订单模型[OrderLogic::class|OrderUnifiedLogic::class]
     */
    public $modelClass;

    /**
     * @var string 订单操作类型
     */
    public $handle;

    /**
     * @var string 操作原因
     */
    public $reason;

    /**
     * @var OrderLogic|OrderUnifiedLogic|null 订单模型
     */
    private $_model = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['order_id', 'user_id', 'operator'], 'integer'],
            [['order_id', 'modelClass', 'handle'], 'required'],
            ['handle', 'in', 'range' => static::getConstants('handle'), 'message' => '不支持的操作类型'],
            [['order_id'], 'validateOrder'],
            [['reason'], 'string'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'order_id' => '订单',
            'user_id' => '用户',
            'handle' => '操作类型',
            'modelClass' => '订单模型信息',
        ];
    }

    /**
     * 校验订单信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateOrder($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $modelClass = $this->modelClass;
        if (!$modelClass) {
            return $this->addError($attribute, '订单信息不存在');
        }
        $query = $modelClass::find()->active()->andWhere([
            'and',
            ['id' => $this->$attribute],
            ['user_id' => $this->user_id],
        ]);
        $model = $query->one();
        if (!$model) {
            return $this->addError($attribute, '订单信息不存在或状态已变更');
        }
        if ($this->validateHandleMethod($model) === false) {
            return $this->addError($attribute, '订单状态已变更！');
        }
        $this->afterValidateOrder($attribute, $model);
        $this->_model = $model;
    }

    /**
     * 订单内部操作是否被允许
     * @param OrderLogic|OrderUnifiedLogic $model
     * @return bool|null
     */
    public function validateHandleMethod($model) {
        $method = 'getCan' . ucfirst($this->handle);
        $handler = array($model, $method);
        if ($model->hasMethod($method) && is_callable($handler)) {
            return call_user_func($handler);
        }
        return null;
    }

    /**
     * 订单附加扩展校验
     * @param string $attribute
     * @param OrderLogic|OrderUnifiedLogic $model
     */
    public function afterValidateOrder($attribute, $model) {
        Yii::info([
            $attribute,
            $model->attributes,
        ], __METHOD__);
    }

    /**
     * 订单信息模型
     * @return OrderLogic|OrderUnifiedLogic|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 执行订单操作并保存
     * @return OrderLogic|OrderUnifiedLogic
     * @throws ModelHttpException
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('订单操作失败');
        }
        return $this->executeTransaction($this->handle);
    }

}
